package vfs.common.file;

import vfs.common.User;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * User: serge
 * Date: 15.11.13
 * Time: 7:10
 */
public class VirtualFile implements Serializable
{
    /* Metadata */
    /** Directory flag */
    private boolean d = false;
    /** Lock flag */
    private boolean l = false;
    /** Lock users */
    private Map<String, User> lu = new HashMap<>();

    /* Actually file */
    private String name;
    /** VirtualFile data. If directory flag is set should be interpreted as Set<VirtualFile> otherwise is a String */
    private Object data;

    /** Creates regular file */
    public VirtualFile(String name)
    {
        this.name = name;

        //        data = new String();
        // uncomment to use data in files
    }

    /** For creating directories */
    public VirtualFile(boolean d, String name)
    {
        this.d = d;
        this.name = name;

        data = new TreeMap<>();
    }

    public boolean isD()
    {
        return d;
    }

    public boolean isL()
    {
        return l;
    }

    public void setL(boolean l)
    {
        this.l = l;
    }

    public Map<String, User> getLu()
    {
        return lu;
    }

    /**
     *
     * @param user
     * @return true if file was locked by user supplied
     */
    public boolean addLu(User user)
    {
        Map.Entry<String, User> e = new HashMap.SimpleEntry<>(user.getName(), user);
        return lu.entrySet().add(e);
    }

    public boolean removeLu(User user)
    {
        return lu.entrySet().remove(user.getName());
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Map<String, VirtualFile> getData()
    {
        return d ? (Map<String, VirtualFile>) data : null;
    }

    public void setData(Object data)
    {
        this.data = data;
    }

    /**
     * Equals works only by name to prevent directory Set<VirtualFile> from having duplicates.
     * Consider something like deepEquals to compare file by contents
     */
    @Override
    public boolean equals(Object o)
    {
        if (this == o)
        {
            return true;
        }
        if (o == null || getClass() != o.getClass())
        {
            return false;
        }

        VirtualFile file = (VirtualFile) o;

        if (!name.equals(file.name))
        {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode()
    {
        return name.hashCode();
    }
}

